#!/bin/bash
#iterates through a directory, uploading each file to your Nirvanix account.

MIN_ARGS=5
E_OPTERROR=65

if [ $# -lt $MIN_ARGS ]
then
    echo "Usage: `basename $0` path uploadDir AppKey Username Password [optional overwite true/false]"
        exit $E_OPTERROR
fi

overwrite="true"
if [ "$6" = "false" ]
then
    overwrite="false";
fi

# Do a login and get the session token
session_token=$(curl 'http://services.nirvanix.com/ws/Authentication/Login.ashx?appKey='$3'&username='$4'&password='$5 | grep SessionToken | awk -F'[<\"][^>\"]*[>\"]' '/SessionToken/{print $2}');

# use find to go through every directory and upload the files to node 1 to a tree.
for i in `find $1 -type f`;
do
    # Get current directory from the file
    upload_dir=$(dirname $i);
    # Get the storage node and token to upload this file.
    ##############
    ##
    ## This will overwrite files unless you pass a 6th optional parameter!
    ##
    ##############
    file_size=1000
    #$(stat -c%s $i)
    storage_info=$(curl 'http://services.nirvanix.com/ws/IMFS/GetStorageNodeExtended.ashx?&fileOverwrite='$overwrite'&ipRestricted=true&destFolderPath='$2$upload_dir'&sizeBytes='$file_size'&firstByteExpiration=6000&lastByteExpiration=259200&sessionToken='$session_token);
    # Extract token from returned results.
    upload_token=$(echo "$storage_info" | grep UploadToken | awk -F'[<\"][^>\"]*[>\"]' '/UploadToken/{print $2}')
    # Extract host from returned results.
    upload_host=$(echo "$storage_info" | awk -F'[<\"][^>\"]*[>\"]' '/UploadHost/{print $2}')
    # Do the upload using the host, file and token.
    curl -F 'upload=@'${i} 'http://'$upload_host'/Upload.ashx?uploadToken='$upload_token'&destFolderPath='$2$upload_dir;
done
